package com.sun.showcase.biz.mall.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.base.Objects;
import com.sun.showcase.biz.basic.service.BaseseCodingRuleService;
import com.sun.showcase.biz.mall.dao.GoodsDao;
import com.sun.showcase.biz.mall.service.GoodsService;
import com.sun.showcase.biz.mall.service.ShoppingCartService;
import com.sun.showcase.biz.mall.service.SkuAttributeService;
import com.sun.showcase.biz.mall.service.SkuAttributeValueService;
import com.sun.showcase.biz.mall.service.SkuService;
import com.sun.showcase.client.domain.mall.Goods;
import com.sun.showcase.client.domain.mall.Sku;
import com.sun.showcase.client.domain.mall.SkuAttribute;
import com.sun.showcase.client.query.mall.GoodsQuery;
import com.sun.showcase.client.query.mall.KVObject;
import com.sun.showcase.client.query.mall.ShoppingCartQuery;
import com.sun.showcase.client.query.mall.SkuAttributeQuery;
import com.sun.showcase.client.query.mall.SkuAttributeValueQuery;
import com.sun.showcase.client.query.mall.SkuQuery;
import com.sun.showcase.pojo.DataGrid;
import com.sun.showcase.pojo.Pager;
import com.sun.showcase.utils.LoginContextHolder;
import com.sun.showcase.utils.StringConstant;
import com.sun.showcase.utils.UuidUtil;
@Service("goodsService")
@Transactional
public class GoodsServiceImpl implements GoodsService{
	@Autowired
	private GoodsDao goodsDao;
	@Autowired
	private SkuAttributeService skuAttributeService;
	@Autowired
	private SkuAttributeValueService skuAttributeValueService;
	@Autowired
	private SkuService skuService;
	@Autowired
	private BaseseCodingRuleService baseseCodingRuleService;
	@Autowired
	private ShoppingCartService shoppingCartService;
	
	public void setGoodsDao(GoodsDao dao) {
		this.goodsDao = dao;
	}

	public DataGrid datagrid(GoodsQuery goodsQuery) {
		DataGrid j = new DataGrid();
		Pager<Goods> pager  = find(goodsQuery);
		j.setRows(getQuerysFromEntitys(pager.getRecords()));
		j.setTotal(pager.getTotalRecords());
		return j;
	}

	private String getNextCode() {
		return baseseCodingRuleService.getNextCodeById(1L);
	}
	
	private List<GoodsQuery> getQuerysFromEntitys(List<Goods> goodss) {
		List<GoodsQuery> goodsQuerys = new ArrayList<GoodsQuery>();
		if (goodss != null && goodss.size() > 0) {
			SkuAttributeQuery aq = new SkuAttributeQuery();
			SkuAttributeValueQuery avq = new SkuAttributeValueQuery();
			SkuQuery sq = new SkuQuery();
			for (Goods tb : goodss) {
				GoodsQuery b = new GoodsQuery();
				BeanUtils.copyProperties(tb, b);
				goodsQuerys.add(b);
				aq.setGoodsId(b.getId());
				aq.setOrderColum("order_num");
				aq.setOrderRule("ASC");
				List<SkuAttributeQuery> aqList = skuAttributeService.listAll(aq);
				for(SkuAttributeQuery saq: aqList) {
					avq.setSkuArributeId(saq.getId());
					saq.setLeaf(skuAttributeValueService.listAll(avq));
				}
				b.setAttrList(aqList);
				sq.setGoodsId(b.getId());
				List<SkuQuery> skuList = skuService.listAll(sq);
				for(SkuQuery skq : skuList) {
					skq.setSkus(JSON.parseArray(skq.getSkuJsonValue(),KVObject.class));
				}
				b.setSkuList(skuList);
			}
		}
		return goodsQuerys;
	}

	private Pager<Goods> find(GoodsQuery goodsQuery) {
		Page<Goods> page = PageHelper.startPage(goodsQuery.getPage().intValue(), goodsQuery.getRows().intValue());
		List<Goods> list = goodsDao.findList(goodsQuery);
		Pager<Goods> pager = new Pager<Goods>();
		pager.setRecords(list);
		pager.setTotalRecords(page.getTotal());
		return  pager;
		
	}
	


	public Goods add(GoodsQuery goodsQuery) {
		Goods t = new Goods();
		goodsQuery.setCode(this.getNextCode());
		BeanUtils.copyProperties(goodsQuery, t);
		t.setActiveFlag(StringConstant.ONE);
		t.setCreateBy(LoginContextHolder.get().getUserId());
		t.setCreateByName(LoginContextHolder.get().getUserName());
		t.setCreateDate(new Date());
	    t.setModifiedBy(LoginContextHolder.get().getUserId());
	    t.setModifiedByName(LoginContextHolder.get().getUserName());
	    t.setModifiedDate(new Date());
	    t.setId(UuidUtil.get32UUID());
	    t.setSellCount(0);
	    if(StringUtils.isNoneBlank(goodsQuery.getImgList())) {
	    	t.setMainImg(goodsQuery.getImgList().split(",")[0]);
	    }
		goodsDao.save(t);
		goodsQuery.setId(t.getId());
		Map<String,String> atrMap = new HashMap<String,String>();
		Map<String,String> atvMap = new HashMap<String,String>();
		
		if(goodsQuery.getAttrList() != null && goodsQuery.getAttrList().size()>0) {
			SkuAttribute sa = null;
			int i=1;
			for(SkuAttributeQuery attr : goodsQuery.getAttrList()) {
				attr.setValue(attr.getValue());
				attr.setGoodsId(t.getId());
				attr.setGoodsName(t.getName());
				attr.setOrderNum(i);
				i++;
				sa = skuAttributeService.add(attr);
				atrMap.put(sa.getValue(), sa.getId());
				for(SkuAttributeValueQuery sav : attr.getLeaf()) {
					sav.setSkuArributeId(sa.getId());
					sav.setGoodsId(t.getId());
					skuAttributeValueService.add(sav);
					atvMap.put(sav.getValue(), sav.getId());
				}
			}
		}
		Double firstGuidePrice = null;
		Double firstSellPrice = null;
		if(goodsQuery.getSkuList() != null && goodsQuery.getSkuList().size()>0) {
			int index=0;
			for(SkuQuery sku : goodsQuery.getSkuList()) {
				if(index==0) {
					firstGuidePrice = sku.getGuidePrice();
					firstSellPrice = sku.getSellPrice();
				}
				index++;
				sku.setGoodsId(t.getId());
				sku.setGoodsName(t.getName());
				sku.setName(t.getName());
				sku.setSellCount(0);
				sku.setSellCountTotal(0);
				int i=0;
				for(KVObject kv : sku.getSkus()) {
					sku.setName(sku.getName()+"【"+kv.getK()+":"+kv.getV()+"】");
					if(i==0) {
						sku.setSkuAttributeId(atrMap.get(kv.getK())+"-"+atvMap.get(kv.getV()));
					}else {
						sku.setSkuAttributeId(sku.getSkuAttributeId()+"_"+atrMap.get(kv.getK())+"-"+atvMap.get(kv.getV()));
					}
					i++;
				}
				sku.setSkuJsonValue(JSON.toJSONString(sku.getSkus()));
				skuService.add(sku);
			}
		}
		//sku 第一个价格用于列表展示
		GoodsQuery update = new GoodsQuery();
		update.getSearchMap().put(StringConstant.ID, t.getId());
		update.setSellPrice(firstSellPrice);
		update.setGuidePrice(firstGuidePrice);
		this.updatePart(update);
		return t;
		
	}

	public void update(GoodsQuery goodsQuery) {
		Goods t = goodsDao.getById(goodsQuery.getId());
	    if(t != null) {
	    	//商品下架 删除购物车
	    	if("0".equals(goodsQuery.getPublishStatus())
	    			&& !"0".equals(t.getPublishStatus())) {
	    		shoppingCartService.deleteByGoodsId(t.getId());
	    	}
	    	//运费方案变化，同步购物车
	    	if(Objects.equal(t.getFreightId(), goodsQuery.getFreightId())) {
	    		shoppingCartService.updateFreightByGoodsId(t.getId(), goodsQuery.getFreightId());
	    	}
	    	BeanUtils.copyProperties(goodsQuery, t);
		    t.setModifiedBy(LoginContextHolder.get().getUserId());
		    t.setModifiedByName(LoginContextHolder.get().getUserName());
		    t.setModifiedDate(new Date());
		    if(StringUtils.isNoneBlank(goodsQuery.getImgList())) {
		    	t.setMainImg(goodsQuery.getImgList().split(",")[0]);
		    }
	    	goodsDao.update(t);
	    	
	    	Map<String,String> atrMap = new HashMap<String,String>();
			Map<String,String> atvMap = new HashMap<String,String>();
			if(goodsQuery.getAttrList() != null && goodsQuery.getAttrList().size()>0) {
				List<String> delAttrIds = new ArrayList<String>();
				List<String> delAttrValueIds = new ArrayList<String>();
				int i=0;
				for(SkuAttributeQuery attr : goodsQuery.getAttrList()) {
					if(StringUtils.isNotEmpty(attr.getId()) && attr.getId().length() != 32) {
						//不是uuid
						attr.setValue(attr.getValue());
						attr.setGoodsId(t.getId());
						attr.setGoodsName(t.getName());
						attr.setOrderNum(i);
						i++;
						skuAttributeService.add(attr);
					}else {
						i=i+attr.getOrderNum();
					}
					atrMap.put(attr.getValue(), attr.getId());
					delAttrIds.add(attr.getId());
					for(SkuAttributeValueQuery sav : attr.getLeaf()) {
						if(StringUtils.isNotEmpty(sav.getId()) && sav.getId().length() != 32) {
							//不是uuid
							sav.setSkuArributeId(attr.getId());
							sav.setGoodsId(t.getId());
							skuAttributeValueService.add(sav);
						}
						atvMap.put(sav.getValue(), sav.getId());
						delAttrValueIds.add(sav.getId());
					}
				}
				if(delAttrIds.size()>0) {
					//删除被删除的数据
					skuAttributeService.deleteNotInIds(delAttrIds,t.getId());
				}
				if(delAttrValueIds.size()>0) {
					//删除被删除的数据
					skuAttributeValueService.deleteNotInIds(delAttrValueIds,t.getId());
				}
			}
			Double firstGuidePrice = null;
			Double firstSellPrice = null;
			if(goodsQuery.getSkuList() != null && goodsQuery.getSkuList().size()>0) {
				List<String> delSkuIds = new ArrayList<String>();
				int index=0;
				for(SkuQuery sku : goodsQuery.getSkuList()) {
					if(index==0) {
						firstGuidePrice = sku.getGuidePrice();
						firstSellPrice = sku.getSellPrice();
					}
					index++;
					sku.setGoodsId(t.getId());
					sku.setGoodsName(t.getName());
					sku.setName(t.getName());
					
					int i=0;
					for(KVObject kv : sku.getSkus()) {
						sku.setName(sku.getName()+"【"+kv.getK()+":"+kv.getV()+"】");
						if(i==0) {
							sku.setSkuAttributeId(atrMap.get(kv.getK())+"-"+atvMap.get(kv.getV()));
						}else {
							sku.setSkuAttributeId(sku.getSkuAttributeId()+"_"+atrMap.get(kv.getK())+"-"+atvMap.get(kv.getV()));
						}
						i++;
					}
					sku.setSkuJsonValue(JSON.toJSONString(sku.getSkus()));
					if(StringUtils.isNotEmpty(sku.getId()) && sku.getId().length() == 32) {
						skuService.update(sku);
						//同步更新购物车
						ShoppingCartQuery updateCart = new ShoppingCartQuery();
						updateCart.setSkuId(sku.getId());
						updateCart.setSellPrice(sku.getSellPrice());
						updateCart.setSkuAttributeId(sku.getSkuAttributeId());
						updateCart.setSkuJsonValue(sku.getSkuJsonValue());
						shoppingCartService.updateBySkuId(updateCart);
					}else {
						sku.setSellCount(0);
						sku.setSellCountTotal(0);
						skuService.add(sku);
					}
					delSkuIds.add(sku.getId());
				}
				
				if(delSkuIds.size()>0) {
					List<Sku> skus= skuService.selectNotInIds(delSkuIds, t.getId());
					for(Sku del : skus) {
						//同步更新购物车	
						shoppingCartService.deleteBySkuId(del.getId());
					}
					//删除被删除的数据
					skuService.deleteNotInIds(delSkuIds,t.getId());
				}
			}
			
			//sku 第一个价格用于列表展示
			GoodsQuery update = new GoodsQuery();
			update.getSearchMap().put(StringConstant.ID, t.getId());
			update.setSellPrice(firstSellPrice);
			update.setGuidePrice(firstGuidePrice);
			this.updatePart(update);
		}
	}
	/**
	 * 根据条件更新部分字段   新建一个query封装需要更新的字段
	 * searchMap封装更新条件
	 * */
	public void updatePart(GoodsQuery goodsQuery) {
	    goodsDao.updatePart(goodsQuery);
	}

	public void delete(java.lang.String[] ids) {
		goodsDao.deleteAc(ids);
	}
	
	//逻辑删除 更新状态位
	public void deletePt(java.lang.String[] ids) {
		goodsDao.deletePt(ids);
	}

	public Goods get(GoodsQuery goodsQuery) {
		return goodsDao.getById(goodsQuery.getId());
	}

	public Goods get(String id) {
		return goodsDao.getById(id);
	}

	
	public List<GoodsQuery> listAll(GoodsQuery goodsQuery) {
	    List<Goods> list = goodsDao.findList(goodsQuery);
	    List<GoodsQuery> goodsQuerys = new ArrayList<GoodsQuery>();
		if (list != null && list.size() > 0) {
			for (Goods tb : list) {
				GoodsQuery b = new GoodsQuery();
				BeanUtils.copyProperties(tb, b);
				goodsQuerys.add(b);
			}
		}
		return goodsQuerys;
	}

	@Override
	public GoodsQuery get4App(String id) {
		Goods g = this.get(id);
		GoodsQuery gq = new GoodsQuery();
		BeanUtils.copyProperties(g, gq);
		SkuQuery skuQuery = new SkuQuery();
		skuQuery.setGoodsId(gq.getId());
		List<SkuQuery> skuList = skuService.listAll(skuQuery);
		gq.setSkuList(skuList);
		SkuAttributeQuery skuAttributeQuery = new SkuAttributeQuery();
		skuAttributeQuery.setGoodsId(gq.getId());
		skuAttributeQuery.setOrderColum("order_num");
		skuAttributeQuery.setOrderRule("ASC");
		List<SkuAttributeQuery> attrList = skuAttributeService.listAll(skuAttributeQuery);
		for(SkuAttributeQuery q : attrList) {
			SkuAttributeValueQuery skuAttributeValueQuery = new SkuAttributeValueQuery();
			skuAttributeValueQuery.setSkuArributeId(q.getId());
			List<SkuAttributeValueQuery> leaf = skuAttributeValueService.listAll(skuAttributeValueQuery);
			q.setLeaf(leaf);
		}
		gq.setAttrList(attrList);
		return gq;
	}

	@Override
	public DataGrid homeDatagrid(GoodsQuery goodsQuery) {
		DataGrid j = new DataGrid();
		Page<Goods> page = PageHelper.startPage(goodsQuery.getPage().intValue(), goodsQuery.getRows().intValue());
		List<Goods> list = goodsDao.homeList(goodsQuery);
		Pager<Goods> pager = new Pager<Goods>();
		pager.setRecords(list);
		pager.setTotalRecords(page.getTotal());
		j.setRows(getQuerysFromEntitys(pager.getRecords()));
		j.setTotal(pager.getTotalRecords());
		return  j ;
	}

	@Override
	public void updateSellCount(String id, Integer buyNum) {
		goodsDao.updateSellCount(id, buyNum);
	}
	
	
}
